package com.aiphome.controller;

import com.aiphome.model.AiService;
import com.aiphome.service.AiServiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/ai-services")
public class AiServiceController {

    @Autowired
    private AiServiceService aiServiceService;

    // 创建新服务
    @PostMapping
    public ResponseEntity<AiService> createService(@RequestBody AiService aiService) {
        AiService createdService = aiServiceService.createService(aiService);
        return new ResponseEntity<>(createdService, HttpStatus.CREATED);
    }

    // 根据ID获取服务
    @GetMapping("/{id}")
    public ResponseEntity<AiService> getServiceById(@PathVariable Long id) {
        Optional<AiService> service = aiServiceService.getServiceById(id);
        return service.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    // 获取所有服务
    @GetMapping
    public ResponseEntity<List<AiService>> getAllServices() {
        List<AiService> services = aiServiceService.getAllServices();
        return ResponseEntity.ok(services);
    }

    // 分页获取服务
    @GetMapping("/paginated")
    public ResponseEntity<Page<AiService>> getServicesWithPagination(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Page<AiService> servicesPage = aiServiceService.getServicesWithPagination(page, size);
        return ResponseEntity.ok(servicesPage);
    }

    // 更新服务
    @PutMapping("/{id}")
    public ResponseEntity<AiService> updateService(@PathVariable Long id, @RequestBody AiService aiService) {
        Optional<AiService> existingService = aiServiceService.getServiceById(id);
        if (existingService.isPresent()) {
            aiService.setId(id); // 确保ID一致
            AiService updatedService = aiServiceService.updateService(aiService);
            return ResponseEntity.ok(updatedService);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 删除服务
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteService(@PathVariable Long id) {
        Optional<AiService> existingService = aiServiceService.getServiceById(id);
        if (existingService.isPresent()) {
            aiServiceService.deleteService(id);
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据服务类型获取活跃服务（演示条件查询）
    @GetMapping("/type/{serviceType}")
    public ResponseEntity<List<AiService>> getActiveServicesByType(@PathVariable String serviceType) {
        List<AiService> services = aiServiceService.getActiveServicesByType(serviceType);
        return ResponseEntity.ok(services);
    }

    // 获取准确度最高的服务（演示排序）
    @GetMapping("/top/{limit}")
    public ResponseEntity<List<AiService>> getTopServicesByAccuracy(@PathVariable int limit) {
        List<AiService> topServices = aiServiceService.getTopServicesByAccuracy(limit);
        return ResponseEntity.ok(topServices);
    }

    // 批量创建服务
    @PostMapping("/batch")
    public ResponseEntity<List<AiService>> batchCreateServices(@RequestBody List<AiService> services) {
        List<AiService> createdServices = aiServiceService.batchCreateServices(services);
        return new ResponseEntity<>(createdServices, HttpStatus.CREATED);
    }

    // 更新服务状态
    @PatchMapping("/{id}/status")
    public ResponseEntity<AiService> updateServiceStatus(
            @PathVariable Long id, 
            @RequestParam boolean active) {
        try {
            aiServiceService.updateServiceStatus(id, active);
            Optional<AiService> updatedService = aiServiceService.getServiceById(id);
            return updatedService.map(ResponseEntity::ok)
                    .orElseGet(() -> ResponseEntity.notFound().build());
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }
}